<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/uuid/8.3.2/uuid.min.js"></script>
</head>

<body>
    <div id="app">
        <form @submit.prevent="insertData">
            <input type="text" v-model="fruit">
            <button type="submit">添加</button>
        </form>
        <ul>
            <li v-for="item,index in list" key="item.id">
                {{item.name}}
                <button @click="modifyData(item.id)">修改</button>
                <button @click="deleteData(item.id)">删除</button>
            </li>
        </ul>
    </div>
    <script>
        var vm = new Vue({
            el: '#app',
            data() {
                return {
                    fruit: '',
                    list: []
                }
            },
            mounted() {
                this.getData();
            },
            methods: {
                // 获取数据
                getData() {
                    axios.get('/fruit').then(res => {
                        this.list = res.data;
                    });
                },
                // 添加数据
                insertData() {
                    if (this.fruit) {
                        axios.post('/fruit', {
                            id: uuid.v1(),
                            fruit: this.fruit
                        }).then(res => {
                            const status = res.data;
                            if (status) {
                                this.getData();
                                this.fruit = '';
                            }
                        });
                    }
                },
                // 修改数据
                modifyData(index) {
                    if (this.fruit) {
                        axios.put(`/fruit/${index}`, {
                            fruit: this.fruit
                        }).then(res => {
                            const status = res.data;
                            if (status) {
                                this.getData();
                            }
                        })
                    }
                },
                // 删除数据
                deleteData(i) {
                    axios.delete(`/fruit/${i}`).then(res => {
                        const status = res.data;
                        if (status) {
                            this.getData();
                        }
                    })
                }
            },
        })
    </script>
</body>

</html>